package com.anntly.netty.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.Random;

/**
 * @Auther: 张文
 * @Date: 2020/6/14 19:14
 * @Description:
 */
public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    Random random = new Random(5);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 5; i++) {
            MessageProtocol messageProtocol = new MessageProtocol();
            String message = "你好啊!"+random.nextInt(100000);
            byte[] content = message.getBytes(CharsetUtil.UTF_8);
            messageProtocol.setLen(content.length);
            messageProtocol.setContent(content);
            ctx.writeAndFlush(messageProtocol);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol messageProtocol) throws Exception {
        System.out.println("接收到服务器消息:"+new String(messageProtocol.getContent(), CharsetUtil.UTF_8));
    }
}
